<style lang="scss">
.cus-tree-editor {
  -moz-animation: 111;
  --plumb-height: 560px;

  .plumb-layout__item-action {
    display: flex;
    align-items: center;
  }
  .plumb-layout .header {
    > * {
      display: flex;
      > *:first-child {
        > *:first-child {
          display: none;
        }
      }
    }
  }
}
.plumbLayoutCls {
  .plumb-layout__tools {
    display: none;
  }
  .plumb-layout__item-delete-btn {
    display: none;
  }
  .plumb-layout__item-input-key {

  }
  .plumb-layout__item-action {
    .el-input {
      display: none;
    }
  }
  .plumb-layout__item-header {
    //min-height: 30px;
  }
  .plumb-layout__header-desc {
    display: none;
    font-size: 0;
  }
  .plumb-layout__header-btn {
    position: absolute;
    left: 10px;
    top: 8px;
  }
  .plumb-layout__plus-btn {
    //display: none;
  }
}
</style>

<template>
  <div class="g-pointer-events-none-modal cus-tree-editor">
    <template v-if="inited">
      <el-row type="flex" align="top" >
        <el-button size="small" @click="openDialog">打开编辑</el-button>
<!--        <el-popover-->
<!--            v-model:visible="state.previewVisible"-->
<!--            placement="bottom"-->
<!--            title=""-->
<!--            :width="600"-->
<!--            trigger="click"-->
<!--        >-->
<!--          <template #reference>-->
<!--            <el-button size="small" @click="toggleVisible">Tree预览</el-button>-->
<!--          </template>-->
<!--          <EwXmlShower :value="getXMLDisplay(state.value)"></EwXmlShower>-->
<!--        </el-popover>-->
      </el-row>
      <el-dialog
          v-model="state.dialogVisible"
          title="数据结构编辑" width="80vw"
          :close-on-click-modal="false"
          @closed="onClosed"
          append-to-body=""
          :lock-scroll="false"
      >
        <div :mode="widgetConfig.mode">
          <el-row class="a-space-mb-10">
<!--            <el-button type="primary" @click="save">保存</el-button>-->
          </el-row>
          <div class="a-space-mb-10">
            <el-row :gutter="10">
             <el-col :span="12">
               <div readonly
                         rows="6"
                         :autofocus="false"
                           style="width: 100%; resize: vertical; border: var(--el-border-base); border-radius: var(--el-border-radius-base)">
  <div class="a-space-mb-10">options语法</div>
  <div>1. label</div>
  <div>2. label|value</div>
              </div>
             </el-col>
              <el-col :span="12">
<!--                <EwXmlShower :value="state.xmlDisplay"></EwXmlShower>-->
                <el-tree default-expand-all :data="state.xmlDisplayObj" >
                  <template #default="{ node, data }">
                    <el-space>
                      <span>{{ data.label }}</span>
                      <span>|</span>
                      <span>{{ data.value }}</span>
                    </el-space>
                  </template>
                </el-tree>
              </el-col>
            </el-row>
          </div>
          <ZLayoutEditor
              :ref="setLayoutRef"
              :controls="false"
              @ele-drag-change="onEleDragChange"
              :store-prefix="storePrefix"
              :auto-load="false"
              @plumb-inited="onPlumbInited"
              @mode:update:all="onPlumbUpdate"
              @save-layout="onSaveLayout"
              drawer-width="350px"
              :handleList1="handleList1"
              :editor-content="editorContent"
              :debug="false"
              plumb-layout-cls="plumbLayoutCls"
              :PlumbLayoutIns="PlumbLayoutIns"
          >
            <template #plumb-layout-items_before="scope">
              <el-input type="textarea"
                        @change="onOptionChange"
                        v-model="scope.dep.data.option"></el-input>
<!--              <template v-if="scope.dep.data.props">-->
<!--                <div>label: {{scope.dep.data.props.label}}</div>-->
<!--                <div>value: {{scope.dep.data.props.value}}</div>-->
<!--              </template>-->
              <h3>子元素</h3>
            </template>
            <template #plumb-layout-item-action-beforeend="scope">
<!--              plumb-layout__item-action-beforeend-->
            </template>
          </ZLayoutEditor>
        </div>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import jsBeautify from 'js-beautify'
import {CustomRenderControlMixin, defineCustomRender} from "@/plugins/form-render/utils";
import ZLayoutEditor from "@/plugins/z-frame/components/ZLayoutEditor.vue";
import {onBeforeUnmount} from "vue";
import {clearPlumbLayoutStorage} from "@/plugins/PlumbLayout/mixin";
import EwXmlShower from "@/components/Ew/EwXmlShower.vue";
import {createEditorConfig} from "@/plugins/ComEditor/editorConfig";
import ZEasyModal from "@/plugins/z-frame/ZEasyModal.vue";

const OPERATE_PREFIX = 'tree-store-prefix'

async function cachedArrOperate(key = '', fun = () => {} ) {
  let cachedKeys = await ZY_EXT.store.getItem(key)
  if (!Array.isArray(cachedKeys)) {
    cachedKeys = []
  }
  // cachedKeys.push(v)
  cachedKeys = await fun(cachedKeys);
  await ZY_EXT.store.setItem(key, cachedKeys)
}

export default {
  name: 'CusTreeEditor',
  components: {ZEasyModal, EwXmlShower, ZLayoutEditor},
  mixins: [
    CustomRenderControlMixin
  ],
  setup(props, ctx) {
    let obj;
    let JSON5 = ZY.JSON5;
    let storePrefix = ZY.rid(6);

    (async function () {
      await cachedArrOperate(OPERATE_PREFIX, (arr) => {
        arr.forEach(cachedKey => {
          clearPlumbLayoutStorage(cachedKey)
        })

        return []
      })
    })();
    let { data, methods, listeners, widgetConfig2, init } = defineCustomRender(props, ctx, {
      handleValueInit(newVal) {
        if (!newVal) {
          newVal = '{data: {links: [], deps: []}, posMap: {}}'
        }
        if (newVal) {
          obj = JSON5.parse(newVal)
        }
        // openDialog()
        return newVal
      }
    })
    let state = data({
      dialogVisible: false,
      previewVisible: false,
      xmlDisplay: '',
      xmlDisplayObj: []
    })
    init(props)

    async function openDialog() {
      state.dialogVisible =true

      await cachedArrOperate(OPERATE_PREFIX, (arr) => {
        return arr.concat([storePrefix])
      })
    }

    function setChange(newVal) {
      let _v = getXMLDisplay(newVal)
      state.xmlDisplay = _v
      // console.log(_v)
      state.xmlDisplayObj = ZY.JSON5.parse(_v)
    }


    async function onPlumbInited({context}) {
      // console.log('handleValueInit', part_key, obj, context)
      await context.importToolsData(obj)
      await ZY.sleep(300)
      await context.saveCache2Storage(obj)
      await ZY.sleep(300)
      // state.xmlDisplay = getXMLDisplay(state.value)
      setChange(state.value)
    }

    let layoutRef = null
    function setLayoutRef(target) {
      layoutRef = target
    }

    function onSaveLayout(e) {
      console.log('onSaveLayout', e)
    }

    function getXML() {
      // let v = layoutRef.getXML()
      // console.log('getXML', v)
    }

    function onEleDragChange() {
      // console.log('onEleDragChange')
    }

    async function save() {
      let v = layoutRef.getToolsData()
      // console.log('getToolsData', v)
      await layoutRef.saveCache2Storage(v)
      let ret = JSON5.stringify(v)

      methods.onChange(ret)
    }

    async function onClosed() {
      await save();
    }

    function getXMLDisplay(v) {
      return jsBeautify.js(getApp().buildTree(v))
    }

    function onPlumbUpdate() {
      // let { model, key, newVal, config } = e
      let v = layoutRef.getToolsData()
      // console.log('onPlumbUpdate', e)
      state.value = JSON5.stringify(v)
    }

    function onOptionChange() {
      onPlumbUpdate()
      setChange(state.value)
    }

    onBeforeUnmount(() => {
      if (layoutRef) {
        layoutRef.clearLayoutStorage()
      }
    })

    let editorContent = createEditorConfig({
      properties: {
        // name: {
        //   type: 'string'
        // },
        // tagName: {
        //   type: 'string',
        //   ui: {
        //     label: '标签名',
        //     widgetConfig: {
        //       readonly: true
        //     }
        //   },
        // },

        // props: {
        //   type: 'object',
        //   properties: {
        //     label: {
        //       type: 'string'
        //     },
        //     value: {
        //       type: 'string'
        //     },
        //   }
        // },
        // options: {
        //   type: 'string',
        //   ui: {
        //     label: 'OPTIONS',
        //     widgetConfig: {
        //       type: 'textarea',
        //       rows: 10
        //     }
        //   },
        // },
        // editText: {
        //   type: 'string',
        //   ui: {
        //     label: '文字',
        //     widgetConfig: {
        //       type: 'textarea'
        //     }
        //   },
        //   computedProp: 'text'
        // },
        attrs: {
          type: 'array',
          ui: {
            label: '属性'
          },
          "items": {
            "type": "object",
            "properties": {
              name: {
                type: 'string',
                ui: {
                  widget: 'CusSuggest',
                  widgetConfig: {
                    placement: 'top'
                  }
                },
              },
              value: {
                type: 'string',
                ui: {
                },
              },
            }
          }
        },
        // textContent: {
        //   type: 'string',
        //   // hidden: true,
        //   ui: {
        //     attrs: [
        //       // ['style', 'height: 0; overflow: hidden']
        //     ],
        //     label: 'text',
        //     widgetConfig: {
        //       type: 'textarea',
        //       rows: 1,
        //       disabled: true,
        //     }
        //   },
        //   computedProp: 'computedEditText'
        // },
      },
      computed: {
        // ui2_styles: `A.get_ui2_styles(MODEL('ui2'))`,
        // computedEditText: "MODEL('editText', '')",
      }
    }, {
      form2: {
        props: {
          label: '',
          value: ''
        }
      }
    })

    function toggleVisible() {
      // state.previewVisible = !state.previewVisible
      if (state.previewVisible) {
        state.previewVisible = false
      } else {
        state.previewVisible = true
      }
    }

    function onDisplayOpened() {
    }


    function handleList1() {
      let elementTags = [
        {
          name: 'name',
          label: '节点',
          data: {
            tagName: 'name',
            attro: {
              // label: 'attro',
              // value: 'attro'
              // options: ''
            },
            // props: {}
          },
        },
      ]
      return elementTags.map(elementTag => {
        return {
          name: elementTag.name,
          label: elementTag.label,
          value: '',
          id: ZY.rid(),
          data: {
            // tagName: elementTag,
            ...elementTag.data
          },
          items: elementTag.items,
          lib: 'control',
          ext: {
            items: [
              {
                name: 'children',
                key: 'children',
              }
            ],
            options: {
              keyReadonly: true
            }
          }
        }
      })
    }

    let PlumbLayoutIns = {
      onEvent(name) {
        // console.log('PlumbLayoutIns', name)
        onPlumbUpdate()
      }
    }

    return {
      state,
      handleList1,
      getXML,
      openDialog,
      onPlumbInited,
      onEleDragChange,
      onClosed,
      PlumbLayoutIns,
      onSaveLayout,
      storePrefix,
      save,
      setLayoutRef,
      onDisplayOpened,
      onOptionChange,
      // setEditorRef,
      editorContent,
      toggleVisible,
      onPlumbUpdate,
      getXMLDisplay,
      widgetConfig: widgetConfig2,
      methods,
      listeners,
    }
  },
}
</script>

